package com.example.cnotebook;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cnotebook.pojo.CategoryInfo;
import com.example.cnotebook.pojo.NoteInfo;
import com.example.cnotebook.pojo.UserInfo;
import com.example.cnotebook.util.ActivityUtils;
import com.example.cnotebook.util.OKHttpUtil;
import com.example.cnotebook.util.UserConstant;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends BaseActivity implements OKHttpUtil.CallBack {
    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbFemPassword;
    private Button btLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private SharedPreferences sp;
    private Thread thread;

    private String loginUrl = "/user/login";

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0x1) {
                progressBar.setVisibility(View.VISIBLE);
            } else {
                progressBar.setVisibility(View.GONE);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etUsername = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
        cbFemPassword = (CheckBox) findViewById(R.id.cb_fem_password);
        btLogin = (Button) findViewById(R.id.bt_login);
        tvRegister = (TextView) findViewById(R.id.tv_register);
        progressBar = findViewById(R.id.progressBar);

        sp = getSharedPreferences("UserInfo", MODE_PRIVATE);
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    login();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivityForResult(intent, 1);
            }
        });

        if (sp.getBoolean("login", false)) {
            String account = sp.getString("account", "");
            String password = sp.getString("password", "");
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("account", account);
                jsonObject.put("password", password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0x1);
            OKHttpUtil.post(loginUrl, jsonObject, this, this);
        }
    }

    private void login() throws JSONException {
        String account = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        if (account.equals("") || password.equals("")) {
            Toast.makeText(this, "账号或者密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", account);
        jsonObject.put("password", password);
        handler.sendEmptyMessage(0x1);
        OKHttpUtil.post(loginUrl, jsonObject, this, this);
    }

    @Override
    public void onSuccess(JSONObject response) throws JSONException {
        handler.sendEmptyMessage(0x2);
        if (response.getInt("code") == 1000) {
            JSONObject data = response.getJSONObject("data");
            Gson gson = new Gson();
            UserInfo user = gson.fromJson(data.getJSONObject("user").toString(), UserInfo.class);
            UserConstant.userInfo = user;
            JSONArray notes = data.getJSONArray("notes");
            JSONArray categories = data.getJSONArray("categories");
            UserConstant.noteInfos.clear();
            UserConstant.categoryInfos.clear();
            for (int i = 0; i < notes.length(); i++) {
                UserConstant.noteInfos.add(gson.fromJson(notes.getJSONObject(i).toString(), NoteInfo.class));
            }
            for (int i = 0; i < categories.length(); i++) {
                UserConstant.categoryInfos.add(gson.fromJson(categories.getJSONObject(i).toString(), CategoryInfo.class));
            }
            sp.edit().putBoolean("login", true).putString("account", user.getAccount()).putString("password", user.getPassword()).apply();
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
            return;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            String account = data.getStringExtra("account");
            etUsername.setText(account);
        }
    }

    @Override
    public void onFailure(int errorNo, String strMsg) {
        handler.sendEmptyMessage(0x2);
        Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        ActivityUtils.getInstance().finishAllActivity();
        System.exit(0);
    }
}
